<template>
  <div>
    <div>
      <a-page-header title="添加积分商品" @back="() => $router.go(-1)" style="background-color: #fff" />
      <page-header-wrapper>
        <a-card :border="false">
          <a-tabs v-model="activeTab">
            <a-tab-pane key="1" tab="基础信息"></a-tab-pane>
            <a-tab-pane key="2" tab="图文设置"></a-tab-pane>
            <a-tab-pane key="4" tab="营销设置"></a-tab-pane>
            <a-tab-pane key="8" tab="自定义表单"></a-tab-pane>
          </a-tabs>
          <a-form-model
            style="margin-top: 20px"
            ref="ruleForm"
            :model="goodsInfo"
            :rules="goodsRules"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 14 }"
          >
            <div v-show="activeTab == 1">
              <a-form-model-item label="">
                <h4 style="font-size: 16px; font-family: PingFangSC-Medium; color: rgba(0, 0, 0, 0.85)">基础信息</h4>
              </a-form-model-item>
              <a-form-model-item label="一键采集">
                <a-input-search
                  :placeholder="'请输入需要采集的商品地址'"
                  :loading="copyLoading"
                  enter-button="商品拉取"
                  @search="goodsCopy"
                  v-model="copyVal"
                >
                </a-input-search>
              </a-form-model-item>
              <a-form-model-item label="商品名称" prop="name">
                <a-input v-model="goodsInfo.name" placeholder="请填写商品名称" />
              </a-form-model-item>
              <a-form-model-item label="商品分类" prop="cat_id">
                <a-select
                  mode="multiple"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择分类"
                  allow-clear
                  v-model="goodsInfo.cat_id"
                >
                  <a-select-option v-for="item in catList" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="关键字" help="能准确搜索到该商品 比如：海尔电视|电视">
                <a-input v-model="goodsInfo.key_word" placeholder="请填写关键字" />
              </a-form-model-item>
              <a-form-model-item label="排序">
                <a-input v-model="goodsInfo.sort" placeholder="请填写商品排序" />
              </a-form-model-item>
              <a-divider />
              <a-form-model-item label="">
                <h4 style="font-size: 16px; font-family: PingFangSC-Medium; color: rgba(0, 0, 0, 0.85)">价格设置</h4>
              </a-form-model-item>
              <a-form-model-item label="售价" prop="price">
                <a-input v-model="goodsInfo.price" type="number" :step="0.01" prefix="￥" suffix="元" />
              </a-form-model-item>
              <a-form-model-item label="兑换积分" prop="integral_price">
                <a-input v-model="goodsInfo.integral_price" type="number" placeholder="请输入兑换积分" :step="1" />
              </a-form-model-item>
              <a-form-model-item label="原价">
                <a-input v-model="goodsInfo.original_price" type="number" :step="0.01" prefix="￥" suffix="元" />
              </a-form-model-item>
              <a-form-model-item label="服务内容" help="例子：正品保障,极速发货,7天退换货。多个请使用英文逗号,分隔">
                <a-input v-model="goodsInfo.service" placeholder="请填写服务内容" />
              </a-form-model-item>
              <a-form-model-item label="单位">
                <a-input v-model="goodsInfo.unit" placeholder="请填写单位" />
              </a-form-model-item>
              <a-form-model-item label="成本价">
                <a-input v-model="goodsInfo.cost_price" type="number" :step="0.01" prefix="￥" suffix="元" />
              </a-form-model-item>
              <a-form-model-item label="已出售量" help="前端展示的销量=实际销量+已出售量">
                <a-input v-model="goodsInfo.virtual_sales" type="number" :step="1" suffix="件" />
              </a-form-model-item>
              <a-divider />
              <a-form-model-item label="">
                <h4 style="font-size: 16px; font-family: PingFangSC-Medium; color: rgba(0, 0, 0, 0.85)">物流设置</h4>
              </a-form-model-item>
              <a-form-model-item label="配送方式" prop="deliverys">
                <a-checkbox-group v-model="checkedList" :options="deliveryOptions" />
              </a-form-model-item>
              <a-form-model-item v-if="checkedList.includes('快递')" label="运费设置" prop="freight">
                <a-select v-model="goodsInfo.freight" placeholder="请选择运费规则">
                  <a-select-option v-for="postageItem in postage" :value="postageItem.id" :key="postageItem.id">
                    {{ postageItem.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-divider />
              <a-form-model-item label="">
                <h4 style="font-size: 16px; font-family: PingFangSC-Medium; color: rgba(0, 0, 0, 0.85)">商品库存</h4>
              </a-form-model-item>
              <a-form-model-item label="商品库存" prop="goods_num">
                <a-input v-model="goodsInfo.goods_num" placeholder="请填写库存" type="number" :step="1" suffix="件" />
              </a-form-model-item>
              <a-form-model-item label="商品货号">
                <a-input placeholder="请填写商品货号" v-model="goodsInfo.goods_no" />
              </a-form-model-item>
            </div>
            <!-- 图文设置 -->
            <div v-show="activeTab == 2">
              <a-form-model-item label="">
                <h4 style="font-size: 16px; font-family: PingFangSC-Medium; color: rgba(0, 0, 0, 0.85)">商品图片</h4>
              </a-form-model-item>
              <a-form-model-item label="商品图片" prop="goods_pic_list">
                <!-- 上传图片 -->
                <cyyUploadImg
                  @uploadSuccess="selectPic"
                  @deleteImg="delPic"
                  :imgList.sync="goodsInfo.goods_pic_list"
                  dataType="list"
                >
                </cyyUploadImg>
              </a-form-model-item>
              <a-form-model-item label="商品视频">
                <!-- 上传视频 -->
                <cyyUploadVideo
                  :videoSrc="goodsInfo.video_url"
                  @uploadSuccess="
                    (e) => {
                      goodsInfo.video_url = e.data
                    }
                  "
                  @deleteVideo="
                    () => {
                      goodsInfo.video_url = ''
                    }
                  "
                ></cyyUploadVideo>
              </a-form-model-item>
              <a-divider />
              <a-form-model-item label="">
                <h4 style="font-size: 16px; font-family: PingFangSC-Medium; color: rgba(0, 0, 0, 0.85)">商品详情</h4>
              </a-form-model-item>
              <a-form-model-item label="图文详情" prop="content">
                <WangEditor
                  :value="content"
                  @change="
                    (e) => {
                      goodsInfo.content = e
                    }
                  "
                ></WangEditor>
                <a-textarea :hidden="true" v-model="goodsInfo.content" />
              </a-form-model-item>
            </div>
            <div v-show="activeTab == 4">
              <a-form-model-item label="">
                <h4 style="font-size: 16px; font-family: PingFangSC-Medium; color: rgba(0, 0, 0, 0.85)">卡劵发放</h4>
              </a-form-model-item>
              <a-form-item label="选择卡劵" help="对应卡券下，必须有允许发放的卡券，同时卡券时效未过期。">
                <div class="inpBox">
                  <a-select
                    mode="multiple"
                    :allowClear="true"
                    placeholder="请选择卡劵"
                    v-model="goods_verify_card_list"
                    @change="cardChange"
                  >
                    <a-select-option v-for="item in verify_list" :key="item.id" :value="item.id">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                  <a-button
                    @click="
                      $router.push({
                        name: 'VerifyList',
                      })
                    "
                    style="margin-left: 10px"
                    type="primary"
                    >卡券管理</a-button
                  >
                </div>
              </a-form-item>
            </div>
            <!-- 商品自定义表单 -->
            <div v-show="activeTab == 8">
              <a-form-model-item label="">
                <h4 style="font-size: 16px; font-family: PingFangSC-Medium; color: rgba(0, 0, 0, 0.85)">自定义表单</h4>
              </a-form-model-item>
              <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否开启">
                <a-radio-group name="radioGroup" v-model="goods_form.is_form">
                  <a-radio :value="1"> 是 </a-radio>
                  <a-radio :value="0"> 否 </a-radio>
                </a-radio-group>
              </a-form-model-item>
              <template v-if="goods_form.is_form == 1">
                <a-form-model-item label="表单名称">
                  <a-input v-model="goods_form.form_name"> </a-input>
                </a-form-model-item>
                <a-form-model-item label="表单设置">
                  <div class="add">
                    <a-select v-model="addType">
                      <a-select-option value="text"> 单行文本 </a-select-option>
                      <a-select-option value="textarea"> 多行文本 </a-select-option>
                      <a-select-option value="time"> 时间选择器 </a-select-option>
                      <a-select-option value="date"> 日期选择器 </a-select-option>
                      <a-select-option value="radio"> 单选 </a-select-option>
                      <a-select-option value="checkbox"> 多选 </a-select-option>
                      <a-select-option value="uploadImg"> 图片上传 </a-select-option>
                    </a-select>

                    <div class="add-action" @click="addList">
                      <a-icon type="plus" />
                    </div>
                  </div>

                  <div class="table">
                    <div class="table-body">
                      <a-row class="title self-th">
                        <a-col :span="4" style="text-align: left"> 类型 </a-col>
                        <a-col :span="4" style="text-align: left"> 名称 </a-col>
                        <a-col :span="4" style="text-align: left"> 提示语 </a-col>
                        <a-col :span="6" style="text-align: left"> 默认值 </a-col>
                        <a-col :span="2" style="text-align: left"> 必填 </a-col>
                        <a-col :span="4" style="text-align: left"> 位置 </a-col>
                      </a-row>
                      <div class="list" @dragover.prevent>
                        <a-row
                          class="item tr-row"
                          v-for="(item, index) in goods_form.form_list"
                          :key="index"
                          :draggable="true"
                          v-dragging="{
                            item: item,
                            list: goods_form.form_list,
                            group: 'row',
                          }"
                        >
                          <a-col :span="4" style="text-align: left">
                            {{
                              item.type == 'text'
                                ? '单行文本'
                                : item.type == 'textarea'
                                ? '多行文本'
                                : item.type == 'time'
                                ? '时间选择器'
                                : item.type == 'date'
                                ? '日期选择器'
                                : item.type == 'radio'
                                ? '单选'
                                : item.type == 'checkbox'
                                ? '多选'
                                : item.type == 'uploadImg'
                                ? '图片上传'
                                : ''
                            }}
                          </a-col>
                          <a-col :span="4" style="text-align: left">
                            <a-input style="width: 100%" v-model="item.name"></a-input>
                          </a-col>
                          <a-col :span="4" style="text-align: left">
                            <a-input
                              style="width: 100%"
                              v-model="item.tip"
                              :placeholder="item.type == 'uploadImg' ? '请选择图片' : ''"
                              v-if="item.type == 'text' || item.type == 'textarea' || item.type == 'uploadImg'"
                            ></a-input>
                          </a-col>
                          <a-col :span="6" style="text-align: left">
                            <a-input
                              v-if="
                                item.type == 'text' ||
                                item.type == 'textarea' ||
                                item.type == 'radio' ||
                                item.type == 'checkbox'
                              "
                              v-model="item.default"
                            ></a-input>
                            <a-time-picker
                              v-model="item.default"
                              v-if="item.type == 'time'"
                              style="max-width: 100%"
                              valueFormat="HH:mm:ss"
                            />
                            <a-date-picker v-model="item.default" v-if="item.type == 'date'" valueFormat="YYYY-MM-DD" />
                            <p v-if="item.type == 'radio' || item.type == 'checkbox'" class="tip" style="color: #888">
                              多个请用英文 , 分开
                            </p>
                            <p
                              v-if="item.type == 'radio' || item.type == 'checkbox'"
                              class="tip"
                              style="color: #d9534f"
                            >
                              注:第一个值默认选中
                            </p>
                          </a-col>
                          <a-col :span="2" style="text-align: left">
                            <a-checkbox
                              :checked="item.required == 1 ? true : item.required == 0 ? false : ''"
                              @change="(e) => changeChecked(e, index)"
                            ></a-checkbox>
                          </a-col>
                          <a-col :span="4" style="text-align: left">
                            <a-button type="danger" size="small" @click="deleteItem(index)">删除</a-button>
                            <a-icon type="unordered-list" style="cursor: move; margin-left: 5px" />
                          </a-col>
                        </a-row>
                      </div>
                    </div>
                  </div>
                  <div class="warning">注：名称最好不要超过4个中文字</div>
                </a-form-model-item>
              </template>
            </div>
            <a-form-model-item :wrapper-col="{ span: 24 }">
              <a-divider style="margin: 0 0 40px 0" />
              <div style="display: flex; justify-content: center">
                <a-button :loading="btnLoading" type="primary" @click="submitAdd" style="margin-right: 8px">
                  保存
                </a-button>
                <a-button @click="$router.back()"> 取消 </a-button>
              </div>
            </a-form-model-item>
          </a-form-model>
        </a-card>
      </page-header-wrapper>
    </div>
    <div>
      <!-- <h1 class="form-title">商品规格</h1>
          <a-form-item
            style="margin-bottom: 24px"
            v-show="productType == 0"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="是否使用规格"
          >
            <a-radio-group @change="onChangeAttr" :disabled="goodsInfo.cloud_goods_id > 0" v-decorator="['use_attr']">
              <a-radio value="1"> 使用 </a-radio>
              <a-radio value="0"> 不使用 </a-radio>
            </a-radio-group>
          </a-form-item> -->
      <!-- 规格选择云仓商品规格不可编辑  只能编辑价格 库存 -->
      <!-- <a-form-item
            v-if="isAttr == 1 && productType == 0"
            :labelCol="{ xs: { span: 0 }, sm: { span: 0 } }"
            :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 } }"
          >
            <a-row style="margin-bottom: 24px" v-if="!(goodsInfo.cloud_goods_id - 0)">
              <a-col :span="2" class="guige-label">商品规格：</a-col>
              <a-col :span="22">
                <a-select
                  show-search
                  placeholder="请选择规格类型"
                  option-filter-prop="children"
                  style="width: 468px"
                  :filter-option="filterOption"
                  @change="attrSelectChange"
                >
                  <a-select-option v-for="(attr, attrIndex) of attrList" :key="attrIndex" :value="attrIndex">
                    {{ attr.name }}
                  </a-select-option>
                </a-select>
              </a-col>
            </a-row>
            <a-row :style="{ marginTop: '10px', marginBottom: '24px' }" v-if="!(goodsInfo.cloud_goods_id - 0)">
              <a-col :span="2" class="guige-label">规格组：</a-col>
              <a-col :span="22">
                <div style="width: 468px">
                  <a-input v-model="addAttrData.groupName" placeholder="添加规格组">
                    <a-icon @click="addAttrGroup" slot="addonAfter" type="plus" />
                  </a-input>
                </div>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="2" class="guige-label">商品规格：</a-col>
              <a-col :span="22">
                <a-row
                  style="padding: 10px"
                  :gutter="0"
                  :style="{ border: '1px solid #f0f0f0', marginBottom: '24px' }"
                  v-for="(attr1, index1) of AttrGroupList"
                  :key="index1"
                >
                  <a-row>
                    <el-tag
                      type="info"
                      effect="plain"
                      size="medium"
                      :closable="!(goodsInfo.cloud_goods_id - 0)"
                      :disable-transitions="false"
                      @close="delAttrGroup(index1)"
                    >
                      {{ attr1.attr_group_name }}
                    </el-tag>
                  </a-row>
                  <a-row align="middle" type="flex">
                    <span style="margin: 10px 10px 0px 0" v-for="(attr2, index2) of attr1.attr_list" :key="index2">
                      <el-tag
                        type="info"
                        effect="plain"
                        size="medium"
                        :closable="!(goodsInfo.cloud_goods_id - 0)"
                        :disable-transitions="false"
                        @close="delAttr(index1, index2)"
                      >
                        {{ attr2.attr_name }}
                      </el-tag>
                    </span>

                    <span style="margin: 10px 10px 0px 0">
                      <a-input-search
                        class="add-guige"
                        @search="e => addAttr(e, index1, attr1.attr_group_name)"
                        size="small"
                        placeholder="添加规格值"
                        v-if="!(goodsInfo.cloud_goods_id - 0)"
                      >
                        <a-icon slot="enterButton" type="plus" />
                      </a-input-search>
                    </span>
                  </a-row>
                </a-row>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="2" class="guige-label"></a-col>
              <a-col :span="22">
                <a-table
                  v-if="GoodsAttr.length > 0"
                  ref="table"
                  :columns="attrColumns"
                  bordered
                  :dataSource="GoodsAttr"
                  size="small"
                  :row-key="(r, i) => JSON.stringify(r)"
                  :pagination="false"
                  class="guige-table"
                >
                  <div slot="numDropdown" slot-scope="setSelectedKeys, selectedKeys" style="padding: 8px">
                    <a-input-search
                      @search="e => settingAll(e, setSelectedKeys, selectedKeys)"
                      size="small"
                      placeholder="批量设置"
                    >
                      <a-icon slot="enterButton" type="plus" />
                    </a-input-search>
                  </div>
                  <div slot="priceDropdown" slot-scope="setSelectedKeys, selectedKeys" style="padding: 8px">
                    <a-input-search
                      @search="e => settingAll(e, setSelectedKeys, selectedKeys)"
                      size="small"
                      placeholder="批量设置"
                    >
                      <a-icon slot="enterButton" type="plus" />
                    </a-input-search>
                  </div>
                  <span slot="attr_list" slot-scope="attr_list">
                    <span style="margin-right: 4px" v-for="(item, index) of attr_list" :key="index">
                      {{ item.attr_name }}
                    </span>
                  </span>
                  <div class="flex-x-center" slot="num" slot-scope="num, attrItem, attrIndex">
                    <a-input-number
                      style="width: 100px"
                      size="small"
                      :autoFocus="autoFocusData.type == 'num' && autoFocusData.index == attrIndex"
                      :value="num"
                      @change="e => handleChange(e, 'num', attrIndex)"
                      placeholder="请输入库存"
                    />
                  </div>
                  <div class="flex-x-center" slot="price" slot-scope="price, attrItem, attrIndex">
                    <a-input
                      type="number"
                      step="0.01"
                      size="small"
                      :autoFocus="autoFocusData.type == 'price' && autoFocusData.index == attrIndex"
                      :value="price"
                      @change="e => handleChange(e.target.value, 'price', attrIndex)"
                      style="width: 100px"
                      placeholder="请输入价格"
                    />
                  </div>
                  <div class="flex-x-center" slot="no" slot-scope="no, attrItem, attrIndex">
                    <a-input
                      style="margin: -5px 0; width: 100px"
                      size="small"
                      :autoFocus="autoFocusData.type == 'no' && autoFocusData.index == attrIndex"
                      :value="no"
                      :disabled="goodsInfo.cloud_goods_id > 0"
                      @change="e => handleChange(e.target.value, 'no', attrIndex)"
                      placeholder="请输入货号"
                    />
                  </div>
                  <template slot="pic" slot-scope="pic, attrItem, attrIndex">
                    <div class="guige-image-box flex-x-center">
                      <div v-if="GoodsAttr[attrIndex].pic" class="goods_pic_item_box">
                        <div class="upload-img-box">
                          <img :src="GoodsAttr[attrIndex].pic" alt="" />
                          <div class="action-hover">
                            <div class="hover-bg"></div>
                            <div class="hover-body">
                              <div class="action-icons">
                                <a-icon @click="previewPic(GoodsAttr[attrIndex].pic)" type="eye" />
                                <a-icon @click="delUrl(attrIndex)" type="delete" />
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="upload-box">
                        <div class="upload-content">
                          <a-icon style="font-size: 14px; color: rgba(0, 0, 0, 0.45)" type="plus" />
                          <span style="font-size: 12px"></span>
                        </div>
                        <div class="self-com">
                          <storage-select selectNum="1" v-model="GoodsAttr[attrIndex].pic"></storage-select>
                        </div>
                      </div>
                    </div>
                  </template>
                </a-table>
              </a-col>
            </a-row>
          </a-form-item> -->
    </div>
  </div>
</template>

<script>
import pick from 'lodash.pick'
import { save, edit, Copy } from '@/api/goods/goods'
import { allCatList as catListApi } from '@/api/plugin/integral'
import { list as attrListApi } from '@/api/goods/attr'
import { WangEditor } from '@/components'
import { findKey } from '@/utils/util'

import { cyyUploadVideo, cyyUploadImg } from '@/components/CyyUi/index'

const goodsInfo = {
  id: 0,
  name: '',
  key_word: '',
  unit: '件',
  price: '',
  weight: 0,
  integral_price: '',
  cost_price: '',
  original_price: '',
  service: '',
  freight: '',
  pieces: '',
  forehead: '',
  quick_purchase: '0',
  video_url: '',
  content: '',
  goods_pic_list: [],
  goods_num: 0,
  goods_no: '',
  integral: { give: 0, forehead: 0, more: '0' },
  use_attr: '0',
  product_type: '4',
  is_negotiable: '0',
  cover_pic: '',
  individual_share: '0',
  share_type: '0',
  share_commission_first: 0.0,
  share_commission_second: 0.0,
  share_commission_third: 0.0,
  cat_id: [],
  attr_setting_type: 0,
  is_level: '0',
  deliverys: [],
  sort:'',
  service_book: { data: [], date: 0, flag: 1 },
}

const attrColumns = [
  {
    title: '规格',
    dataIndex: 'attr_list',
    maxWidth: 450,
    scopedSlots: { customRender: 'attr_list' },
  },
  {
    title: '库存',
    dataIndex: 'num',
    maxWidth: 200,
    scopedSlots: {
      filterDropdown: 'numDropdown',
      filterIcon: 'numIcon',
      customRender: 'num',
    },
  },
  {
    title: '价格',
    dataIndex: 'price',
    maxWidth: 200,
    scopedSlots: {
      filterDropdown: 'priceDropdown',
      filterIcon: 'priceIcon',
      customRender: 'price',
    },
  },
  {
    title: '货号',
    dataIndex: 'no',
    maxWidth: 200,
    scopedSlots: { customRender: 'no' },
    slots: { title: 'customNo' },
  },
  {
    title: '图片',
    dataIndex: 'pic',
    // width: 20,
    scopedSlots: { customRender: 'pic' },
    slots: { title: 'customPic' },
  },
]
export default {
  components: {
    WangEditor,
    cyyUploadVideo,
    cyyUploadImg,
  },
  data() {
    let checkDeliverys = (rule, value, callback) => {
      if (!this.checkedList || !this.checkedList.length) {
        callback(new Error('请选择配送方式'))
      } else {
        callback()
      }
    }
    return {
      goods_form: {
        is_form: '',
        form_name: '',
        form_list: [],
      },
      addType: 'text',
      activeTab: '1',
      copyLoading: false,
      copyVal: '',
      butLoading: false,
      isAttr: 0,
      productType: 0,
      goodsInfo: {},
      postage: [],
      catList: [],
      level: [], // 会员等级
      verify_list: [],
      goods_verify_card_list: [],
      select_cart_id: {},
      GoodsAttr: [], // 遍历后商品提交规格
      AttrGroupList: [], // 处理后的添加规格
      attrList: [], // 可选择类型
      attrColumns: attrColumns, // 商品规格表结构
      autoFocusData: { type: '', index: 0 }, // 获取焦点参数,
      bookFocusData: { index: 0 }, // 预约焦点参数
      addAttrData: { groupName: '' }, // 添加规格数据
      delivery_type: null,
      checkedList: [],
      deliveryOptions: [],
      defaultdeliveryOptions: [],
      goodsId: 0,
      defaultFreight: '',
      verify_card_default: [],
      goodsRules: {
        name: [{ required: true, message: '请填写商品名称', trigger: 'blur' }],
        cat_id: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        price: [{ required: true, message: '请输入商品售价', trigger: 'blur' }],
        integral_price: [{ required: true, message: '请输入商品兑换积分', trigger: 'blur' }],
        deliverys: [{ validator: checkDeliverys, trigger: 'change' }],
        freight: [{ required: true, message: '请选择运费规则', trigger: 'change' }],
        goods_pic_list: [{ required: true, message: '请上传商品图片', trigger: 'blur' }],
        content: [{ required: true, message: '请输入商品详情', trigger: 'blur' }],
      },
      content: '',
    }
  },
  created() {
    this.getCatList()
    this.getAttrList()
    var goodsId = this.$route.query.id ? this.$route.query.id : 0
    this.goodsId = goodsId
    this.getGoodsData(goodsId)
    // console.log(moment().format('YYYY-MM-DD'))
  },
  computed: {
    isEdit() {
      return !!this.$route.query.id
    },
  },
  watch: {
    isAttr(newVal, val) {
      if (newVal > 0) {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            goods_num: 0,
            goods_no: '',
          })
        })
      } else {
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.goodsInfo, ['goods_num', 'goods_no']))
        })
      }
    },
    AttrGroupList(val) {
      this.setGoodsAttr(val)
    },
  },
  methods: {
    delUrl(index) {
      this.GoodsAttr[index].pic = ''
    },
    // 生成日期
    dateNext(d) {
      d = new Date(d)
      d = +d + 1000 * 60 * 60 * 24
      d = new Date(d)
      // 格式化
      const month = d.getMonth() + 1 > 9 ? d.getMonth() + 1 : '0' + (d.getMonth() + 1)
      const date = d.getDate() > 9 ? d.getDate() : '0' + d.getDate()
      return d.getFullYear() + '-' + month + '-' + date
    },
    /**
     * 保存商品
     */
    submitAdd(e) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          try {
            this.butLoading = true
            this.goodsInfo.attr = this.GoodsAttr
            this.goodsInfo.cover_pic = this.goodsInfo.goods_pic_list[0].pic_url
            // values.video_url = this.goodsInfo.video_url
            // values.goods_pic_list = this.goodsInfo.goods_pic_list
            if (this.goods_verify_card_list && this.goods_verify_card_list.length) {
              let cardArr = []
              this.goods_verify_card_list.forEach((item) => {
                this.verify_list.forEach((card) => {
                  if (card.id == item) {
                    cardArr.push(card)
                  }
                })
              })
              this.goodsInfo.goods_verify_card_list = cardArr
            } else {
              this.goodsInfo.goods_verify_card_list = []
            }
            this.goodsInfo.deliverys = this.checkedList
            this.goodsInfo['delivery_type'] = JSON.parse(JSON.stringify(this.goodsInfo.deliverys))
            this.goodsInfo.delivery_type.forEach((d, index) => {
              this.goodsInfo.delivery_type.splice(index, 1, findKey(this.delivery_type, d))
            })
            // values.service_book = this.goodsInfo.service_book
            // values.date_book = this.bookConfig
            this.goodsInfo.form = this.goods_form
            this.goodsInfo.product_type = 4
            // if (this.goodsInfo.id) {
            //   this.goodsInfo.is_change_attr = this.is_change_attr
            // }

            // values.is_change_attr = this.is_change_attr
          } catch (error) {
            console.log(error)
          }
          save(this.goodsInfo).then((res) => {
            this.butLoading = false
            if (res.code == 0) {
              this.$router.go(-1)
              this.$message.success(res.msg)
            } else {
              this.$message.error(res.msg)
            }
          })
          this.butLoading = false
        } else {
          return false
        }
      })
    },
    /**
     * 获取商品详情
     */
    getGoodsData(goodsId) {
      const hide = this.$message.loading('加载中', 0)
      // this.goodsInfo = {}
      edit({ id: goodsId }).then((res) => {
        console.log(res.data, 'info')
        if (res.data.info && res.data.info.id > 0) {
          this.goodsInfo = res.data.info
          this.content = res.data.info.content
        } else {
          this.goodsInfo = JSON.parse(JSON.stringify(goodsInfo))
        }
        const info = res.data.info
        const postage = res.data.postage
        const postageDefault = postage.filter((d) => {
          return d.is_enable == 1
        })
        if (postageDefault.length) {
          this.postage = res.data.postage
        } else {
          this.postage = [{ id: '0', name: '默认' }, ...res.data.postage]
        }
        if (!this.goodsInfo.freight) {
          if (postageDefault.length) {
            this.goodsInfo.freight = postageDefault[0].id
          } else {
            this.goodsInfo.freight = '0'
          }
        }
        this.is_change_attr = 0
        // this.level = res.data.level
        this.verify_list = res.data.verify_list

        if (res.data.goods_verify_card_list.length) {
          res.data.goods_verify_card_list.forEach((item) => {
            this.verify_card_default.push(item.id)
            this.goods_verify_card_list.push(item.id)
          })
        } else {
          this.goods_verify_card_list = []
        }
        if (res.data.info) {
          this.delivery_type = { ...res.data.info.delivery_type, online: '线上发货' }
        } else {
          this.delivery_type = []
        }
        this.goods_form = res.data.info.form
        if (info && info.delivery_type) {
          this.deliveryOptions = Object.values(info.delivery_type)
          this.defaultdeliveryOptions = Object.values(info.delivery_type)
        }
        try {
          const goods_delivery_type = JSON.parse(JSON.stringify(info.goods_delivery_type))
          goods_delivery_type.forEach((d, index) => {
            goods_delivery_type.splice(index, 1, this.delivery_type[d])
          })
          this.checkedList = goods_delivery_type || Object.values(info.delivery_type)
        } catch (err) {
          console.log(err)
        }
        if (res.data.AttrGroupList.length === 0) {
          this.setDefaultAttr()
        } else {
          this.AttrGroupList = res.data.AttrGroupList
        }
        hide()
      })
    },
    // 是否使用规格
    onChangeAttr(val) {
      this.isAttr = val.target.value
    },
    setDefaultAttr() {
      this.GoodsAttr = [
        {
          attr_list: [
            {
              attr_name: '默认',
            },
          ],
          num: 0,
          price: 0,
          supplier_price: 0,
          no: '',
          pic: '',
          share_commission_first: '',
          share_commission_second: '',
          share_commission_third: '',
        },
      ]
    },
    // 获取分类
    getCatList() {
      catListApi().then((res) => {
        this.catList = res.data.data
      })
    },
    /**
     * 获取添加规格类型
     */
    getAttrList() {
      attrListApi().then((res) => {
        this.attrList = res.data.list
      })
    },
    /**
     * 选中规格类型处理
     */
    attrSelectChange(e) {
      var attr = this.attrList[e]
      var AttrGroupList = []
      attr.children.forEach((element) => {
        var attrItem = []
        element.children.forEach((element2) => {
          attrItem.push({
            attr_name: element2.name,
          })
        })
        var attrGroup = {
          attr_group_name: element.name,
          attr_list: attrItem,
        }
        AttrGroupList.push(attrGroup)
      })
      this.AttrGroupList = AttrGroupList

      if (!this.is_change_attr) {
        this.is_change_attr = 1
      }
    },
    /**
     * 规格类型筛选
     */
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    /**
     * 根据添加规格，生成规格数据
     */
    setGoodsAttr(attrGroup) {
      let attrList = []
      attrList = this.setGoodsAttrItem(attrGroup, [], 0)
      this.GoodsAttr = this.getAttrDataInfo(attrList)
    },
    /**
     * 处理规格数据
     */
    setGoodsAttrItem(attrGroup, attrList, index) {
      var attrList1 = []
      if (index < attrGroup.length) {
        if (index === 0 || attrList.length === 0) {
          if (attrGroup[index].attr_list.length > 0) {
            attrGroup[index].attr_list.forEach((element) => {
              element.attr_group_name = attrGroup[index].attr_group_name
              attrList1.push([element])
            })
          }
        } else {
          if (attrGroup[index].attr_list.length > 0) {
            attrList.forEach((element) => {
              attrGroup[index].attr_list.forEach((element1) => {
                element1.attr_group_name = attrGroup[index].attr_group_name
                attrList1.push(element.concat([element1]))
              })
            })
          } else {
            attrList1 = attrList
          }
        }
        ++index
        return this.setGoodsAttrItem(attrGroup, attrList1, index)
      } else {
        return attrList
      }
    },
    /**
     * 获取其他详细数据
     */
    getAttrDataInfo(attr) {
      var attrList = []
      attr.forEach((element) => {
        var setAttr = {}
        if (this.goodsInfo.attr) {
          JSON.parse(this.goodsInfo.attr).forEach((element2) => {
            if (element2.attr_list.length === element.length) {
              var loading = true
              if (loading && this.compareAttr(element2.attr_list, element)) {
                setAttr = element2
                loading = false
              }
            }
          })
        }
        var data = {
          attr_list: element,
          num: setAttr && setAttr.num ? setAttr.num : 0,
          price: setAttr && setAttr.price ? setAttr.price : 0,
          no: setAttr && setAttr.no ? setAttr.no : '',
          pic: setAttr && setAttr.pic ? setAttr.pic : '',
          share_commission_first: setAttr && setAttr.share_commission_first ? setAttr.share_commission_first : '',
          share_commission_second: setAttr && setAttr.share_commission_second ? setAttr.share_commission_second : '',
          share_commission_third: setAttr && setAttr.share_commission_third ? setAttr.share_commission_third : '',
        }
        for (const key in setAttr) {
          if (key.indexOf('member') !== -1) {
            data[key] = setAttr[key]
          }
        }
        attrList.push(data)
      })
      return attrList
    },
    compareAttr(val1, val2) {
      var compareLen = 0
      val1.forEach((element1) => {
        val2.forEach((element2) => {
          if (element1.attr_name === element2.attr_name) {
            compareLen++
          }
        })
      })
      return compareLen === val1.length
    },
    /**
     * 修改规格数据
     */
    handleChange(value, type, index) {
      console.log(value)
      this.autoFocusData = {
        type: type,
        index: index,
      }
      this.GoodsAttr[index][type] = value === null ? '' : value
    },
    /**
     * 添加规格组
     */
    addAttrGroup() {
      if (this.addAttrData.groupName) {
        var data = {
          attr_group_name: this.addAttrData.groupName,
          attr_list: [],
        }
        this.AttrGroupList.push(data)
      }
      this.addAttrData.groupName = ''
      if (!this.is_change_attr) {
        this.is_change_attr = 1
      }
    },
    /**
     * 添加规格值
     */
    addAttr(e, index, groupName) {
      var data = {
        attr_group_name: groupName,
        attr_name: e,
      }
      var attrGroup = this.AttrGroupList
      attrGroup[index].attr_list.push(data)
      this.AttrGroupList = null
      this.AttrGroupList = attrGroup
    },
    /**
     * 删除规格组
     */
    delAttrGroup(index) {
      this.AttrGroupList.splice(index, 1)
      if (!this.is_change_attr) {
        this.is_change_attr = 1
      }
    },
    delAttr(index1, index2) {
      var attrGroup = this.AttrGroupList
      attrGroup[index1].attr_list.splice(index2, 1)
      this.AttrGroupList = null
      this.AttrGroupList = attrGroup
      if (!this.is_change_attr) {
        this.is_change_attr = 1
      }
    },
    settingAll(e, setSelectedKeys, selectedKeys) {
      console.log('selectedKeys', selectedKeys)
      console.log('setSelectedKeys', setSelectedKeys)
      this.GoodsAttr.forEach((element, index) => {
        this.GoodsAttr[index][setSelectedKeys.column.dataIndex] = e
      })
    },
    goodsCopy() {
      if (this.copyVal == '') {
        this.$message.warning('请输入需要采集的商品地址')
        return
      }
      this.copyLoading = true
      const hide = this.$message.loading('拉取中', 0)
      Copy({
        url: this.copyVal,
      })
        .then((res) => {
          if (res.code === 0) {
            var goods = this.goodsInfo
            delete goods.id
            this.goodsInfo = {}
            const pic = []
            goods.content = res.data.desc
            res.data.pics.forEach((item) => {
              pic.push({ pic_url: item })
            })
            goods.goods_pic_list = pic
            if (res.data.price) {
              goods.price = res.data.price
            }

            if (res.data.video) {
              goods.video_url = res.data.video
            }

            goods.virtual_sales = res.data.vagueSellCount

            if (res.data.marketPrice) {
              goods.original_price = res.data.marketPrice
            }

            goods.name = res.data.title
            if (goods.product_type == '0') {
              if (res.data.attr.length === 0) {
                this.setDefaultAttr()
              } else {
                this.AttrGroupList = res.data.attrGroup
                setTimeout(() => {
                  this.GoodsAttr = res.data.attr
                }, 1000)
              }
            }

            goods.use_attr = res.data.attr.length > 0 ? '1' : '0'
            this.goodsInfo = goods
          }
        })
        .catch((error) => {
          this.$message.error('网络错误，请重试')
          console.log(error)
        })
        .then(() => {
          hide()
          this.copyLoading = false
        })
      // }
    },
    delPic(e) {
      this.goodsInfo.goods_pic_list.splice(e.index, 1)
    },
    selectPic(e) {
      this.goodsInfo.goods_pic_list = this.goodsInfo.goods_pic_list ? this.goodsInfo.goods_pic_list : []
      e.data.forEach((ele) => {
        this.goodsInfo.goods_pic_list.push({ pic_url: ele })
      })
      console.log(this.goodsInfo)
    },
    changeChecked(e, index) {
      const checked = e.target.checked ? 1 : 0
      console.log(this.goods_form.form_list)
      this.goods_form.form_list[index].required = checked
    },
    addList() {
      this.goods_form.form_list.push({
        type: this.addType,
        name: '',
        tip: '',
        required: '0',
        sort: '0',
        is_delete: '0',
      })
    },
    deleteItem(index) {
      this.goods_form.form_list.splice(index, 1)
    },
  },
}
</script>
<style scoped lang="less">
.sku-group {
  /deep/.ant-form-item-control-wrapper {
    width: 91%;
  }
}
.item-table {
  width: 100%;
  max-width: 1000px;
  display: inline-block;
}
.item-colunm-content {
  /deep/.ant-checkbox-group {
    display: flex;
    align-items: center;
    label {
      margin-top: 6px;
    }
  }
}
/deep/.ant-form-explain {
  margin-top: 10px;
}
/deep/.ant-tabs-bar {
  margin: 0;
}
/deep/.ant-tabs-nav .ant-tabs-tab {
  padding: 10px 0;
  margin: 0 49px 0 0;
}
.required::before {
  content: '*';
  color: red;
}
td {
  padding: 0 6px;
}
th {
  padding: 0 6px;
}
tr:hover {
  background: #f0f0f0;
}
.goods_pic_item {
  width: 80px;
  height: 80px;
  border-radius: 3px;
}

.upload-box {
  width: 104px;
  height: 104px;
  background: rgba(0, 0, 0, 0.05);
  border: 1px dashed rgba(0, 0, 0, 0.14901960784313725);
  opacity: 1;
  border-radius: 4px;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  float: left;
  .upload-content {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }
  .self-com {
    opacity: 0;
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 111;
    /deep/.ant-btn {
      width: 104px;
      height: 103px;
    }
    /deep/.ant-input-group-wrapper {
      width: 104px;
      height: 104px;
      .ant-input-group {
        width: 100%;
        height: 100%;
        span:nth-child(1) {
          display: none;
        }
        span:nth-child(3) {
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          top: 0;
        }
      }
    }
  }
}

.guige-image-box {
  .upload-box {
    width: 50px;
    height: 50px;
    background: #fff;
    border: 1px solid rgba(0, 0, 0, 0.14901960784313725);
    opacity: 1;
    border-radius: 4px;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    float: left;
    .upload-content {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
    }
    .self-com {
      opacity: 0;
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 111;
      /deep/.ant-btn {
        width: 50px;
        height: 49px;
      }
      /deep/.ant-input-group-wrapper {
        width: 50px;
        height: 50px;
        .ant-input-group {
          width: 100%;
          height: 100%;
          span:nth-child(1) {
            display: none;
          }
          span:nth-child(3) {
            width: 100%;
            height: 100%;
            position: absolute;
            left: 0;
            top: 0;
          }
        }
      }
    }
  }

  .goods_pic_item_box {
    box-shadow: 0 0 5px rgba(170, 170, 170, 0.671);
    border-radius: 3px;
    position: relative;
    margin-right: 10px;
    width: 50px;
    height: 50px;
    background: rgba(0, 0, 0, 0.05);
    border: 1px solid rgba(0, 0, 0, 0.14901960784313725);
    border-radius: 4px;
    float: left;
    margin: 0 8px 0 0px;
    padding: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    .upload-img-box {
      width: 98%;
      height: 98%;
      position: relative;
      .action-hover {
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 11;
        display: none;
        opacity: 0;
        transition: all 0.3s;

        .hover-bg {
          width: 100%;
          height: 100%;
          background-color: #000000;
          opacity: 0.4;
        }
        .hover-body {
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          top: 0;
          z-index: 11;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .action-icons {
          display: flex;
          justify-content: center;
          align-items: center;
          padding: 5px;
          .anticon {
            color: #ffffff;
            font-size: 17px;
          }
          .anticon:nth-child(1) {
            margin-right: 10px;
          }
        }
      }
      img {
        width: 100%;
        height: 100%;
        display: block;
      }
    }
    .upload-img-box:hover > .action-hover {
      display: block;
      opacity: 1;
    }
  }
}

.video-box {
  width: 104px;
  height: 104px;
  position: relative;
  background: rgba(0, 0, 0, 0.05);
  border: 1px dashed rgba(0, 0, 0, 0.14901960784313725);
  opacity: 1;
  border-radius: 4px;
  margin-left: 8px;
  video {
    width: 100%;
    height: 100%;
  }
  .action-hover {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 11;
    display: none;
    opacity: 0;
    transition: all 0.3s;
    background-color: #000000;
    opacity: 0.4;

    .hover-bg {
      width: 100%;
      height: 100%;
      // background-color: #000000;
      // opacity: 0.4;
    }
    .hover-body {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 11;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .action-icons {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 5px;
      .anticon {
        color: #ffffff;
        font-size: 17px;
      }
      .anticon:nth-child(1) {
        margin-right: 10px;
      }
    }
  }
}
.video-box:hover > .action-hover {
  display: block;
}

.goods_pic_item_box {
  width: 80px;
  height: 80px;
  box-shadow: 0 0 5px rgba(170, 170, 170, 0.671);
  border-radius: 3px;
  position: relative;
  margin-right: 10px;
  width: 104px;
  height: 104px;
  background: rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.14901960784313725);
  opacity: 1;
  border-radius: 4px;
  float: left;
  margin: 0 8px 0 0px;
  padding: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  .upload-img-box {
    width: 88px;
    height: 88px;
    position: relative;
    .action-hover {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 11;
      display: none;
      opacity: 0;
      transition: all 0.3s;

      .hover-bg {
        width: 100%;
        height: 100%;
        background-color: #000000;
        opacity: 0.4;
      }
      .hover-body {
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 11;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .action-icons {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 5px;
        .anticon {
          color: #ffffff;
          font-size: 17px;
        }
        .anticon:nth-child(1) {
          margin-right: 10px;
        }
      }
    }
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
  .upload-img-box:hover > .action-hover {
    display: block;
    opacity: 1;
  }
}

.distribution-table {
  /deep/.ant-table-small {
    background: #ffffff;
    border: 1px solid rgba(0, 0, 0, 0.14901960784313725);
    border-radius: 4px;
    .ant-table-body {
      padding: 10px 0;
      margin: 0 12px;
      .ant-table-thead {
        height: 54px;
        background: #fafafa;
        border-radius: 4px 4px 0px 0px;
        border-bottom: 1px solid#E8E8E8;
      }
      tr {
        td {
          padding-top: 15px !important;
          padding-bottom: 15px !important;
        }
      }
    }
  }
}

.goods_pic_item_box .icon {
  position: absolute;
  top: 2px;
  right: 2px;
  /* margin-right: 10px; */
}
.timeSlot {
  display: flex;
  align-items: center;
}
.timePrice div {
  display: flex;
  align-items: center;
  span {
    margin-right: 10px;
    width: 100px;
    min-width: 60px;
  }
}
.tips {
  display: flex;
  flex-direction: column;
  color: #d9534f;
  font-size: 14px;
  span {
    line-height: normal;
  }
}
.add {
  display: inline-block;
  position: relative;
  .add-action {
    position: absolute;
    right: 0;
    top: 0;
    bottom: 0;
    width: 40px;
    /* height: 29px; */
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #ffffff;
    border: 1px solid #d9d9d9;
    cursor: pointer;
    border-left: 0;
  }
}
.warning {
  font-size: 14px;
  font-family: PingFangSC-Regular;
  line-height: 22px;
  color: rgba(0, 0, 0, 0.45);
  margin-top: 10px;
}
.table {
  width: 100%;
  margin-top: 36px;
  padding: 10px 12px;

  background: #ffffff;
  border: 1px solid rgba(0, 0, 0, 0.14901960784313725);
  opacity: 1;
  border-radius: 4px;
  .table-body {
    .ant-row {
      min-height: 54px;
      opacity: 1;
      border-radius: 4px 4px 0px 0px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #e8e8e8;
    }
    .self-th {
      background: #fafafa;
    }
  }
  .title {
    .ant-col {
      text-align: center;
      padding: 0 10px;
      font-size: 14px;
      font-family: PingFangSC-Medium;
      line-height: 22px;
      color: rgba(0, 0, 0, 0.85);
    }
  }
}
.list {
  .item {
    background-color: #fff;
    padding: 5px;
    display: flex;
    align-items: center;
    .ant-col {
      text-align: center;
      padding: 0 10px;
    }
  }
}
.tr-row:hover {
  background-color: #e6f7ff;
}

.tip {
  margin: 0;
  padding: 0;
  font-size: 12px;
  line-height: normal;
  text-align: left;
}
.form-title {
  margin-bottom: 24px;
  width: 64px;
  height: 22px;
  font-size: 16px;
  font-family: PingFangSC-Medium;
  line-height: 24px;
  color: rgba(0, 0, 0, 0.85);
  opacity: 1;
}
.lable-margin24 {
  .ant-form-item-label {
    margin: 24px 0;
  }
}
.guige-table {
  /deep/.ant-table-thead {
    background: #fafafa;
  }
}

.guige-label {
  color: rgba(0, 0, 0, 0.85);
  text-align: right;
}

// 搜索input
.add-guige {
  /deep/.ant-input-wrapper {
    .ant-input {
      width: 172px;
      height: 28px;
    }
    .ant-input-search-button {
      height: 28px;
      line-height: 28px;
      width: 28px;
      text-align: center;
      background: #fff;
      color: rgba(0, 0, 0, 0.45);
      border-color: rgb(217, 217, 217);
    }
  }
}

.inpBox {
  position: relative;
  display: flex;
  align-items: center;
}
</style>
